<template>
  <el-row class="drawerCont">
    <commonDrawer
      :title="drawerType==='edit'?'消息编辑':'消息新增'"
      :drawer="drawer"
      :size="'600px'"
      @closeDraw="openOrCloseDraw"
      @cancelFun="closeDraw"
      @save="handleConfirm"
    >
      <template slot="column">
        <el-form
          class="m7-form drawerForm"
          ref="activePostForm"
          :model="activePostForm"
          :rules="rules"
          label-position="top"
        >
          <el-form-item label="消息名称" prop="name">
            <el-input
              v-model="activePostForm.name"
              placeholder="请输入消息名称"
              clearable
              disabled
            />
          </el-form-item>
          <el-form-item label="消息类型" prop="type">
            <el-select
              v-model="activePostForm.type"
              placeholder="请选择消息类型"
              disabled
            >
              <el-option v-for="i in typeOptions" :key="i.value" :value="i.value" :label="i.label" />
            </el-select>
          </el-form-item>
          <el-form-item label="消息内容" prop="content">
            <span slot="label">消息内容
              <el-tooltip
                class="item"
                effect="dark"
                placement="bottom">
                <div slot="content" v-html="activePostForm.contentTips || '暂无说明'"></div>
                <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42"></span>
              </el-tooltip>
            </span>
            <el-input
              v-model="activePostForm.content"
              placeholder="请输入消息内容"
              clearable
              type="textarea"
              :rows="4"
            />
          </el-form-item>
          <el-form-item label="消息级别规则" prop="level">
            <el-select
              v-model="activePostForm.level"
              placeholder="请选择消息级别规则"
              multiple
              filterable
              allow-create
              disabled
            >
              <!-- collapse-tags -->
              <el-option v-for="i in []" :key="i" :value="i" :label="i" />
            </el-select>
          </el-form-item>
          <el-form-item label="触达人员">
            <div class="visiblePersonnelTransfer">
              <tree-transfer
                height="400px"
                mode="transfer"
                :from_data="transferFromData"
                :to_data="visiblePersonnel"
                :defaultProps="{ label: 'label' }"
                :title="['未选人员', '已选人员']"
                :button_text="['加入选项', '移出选项']"
                placeholder="请输入角色/技能组/座席"
                @add-btn="add"
                @remove-btn="remove"
                :high-light="true"
                filter
                openAll
              ></tree-transfer>
            </div>
          </el-form-item>
          <el-form-item label="触达规则" prop="rules">
            <el-select
              v-model="activePostForm.rules"
              placeholder="请选择触达规则"
              filterable
              disabled
            >
              <el-option v-for="i in rulesOptions" :key="i.value" :value="i.value" :label="i.label" />
            </el-select>
          </el-form-item>
          <el-form-item label="触达方式" prop="remindWay">
            <el-select
              v-model="activePostForm.remindWay"
              placeholder="请选择触达方式"
              multiple
              filterable
              default-first-option
            >
              <el-option v-for="i in remindWayOptions" :key="i.value" :value="i.value" :label="i.label" />
            </el-select>
          </el-form-item>
        </el-form>
      </template>
    </commonDrawer>
  </el-row>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import treeTransfer from 'el-tree-transfer';
import commonDrawer from '@/common/views/drawer/index.vue';
import { deepClone } from '@/utils/common';
import { Store } from 'vuex';
@Component({
  name: 'customerTemplateSettingCUDrawer',
  components: {
    commonDrawer,
    treeTransfer
  }
})
export default class CustomerTemplateSetting extends Vue {
  // #region 基础数据
  @Prop(Object) public postForm!: any;
  @Prop({ default: 'add' }) private drawerType!: string;
  private $store: Store<any> | undefined
  private drawer: boolean = false;
  private activePostForm: any = {};
  private visiblePersonnel: any = []; // 已选中的触达人员
  private transferFromData: any = [];

  @Watch('postForm')
  private onParentValue (newValue: any) {
    const before = JSON.stringify(this.activePostForm)
    const after = JSON.stringify(newValue)
    // 如果跟上次点开的一样，就不重复渲染了
    if (before === after) {
      // 需要重新渲染，否则新增角色、技能组，没有重新获取
      // return false
    }
    this.activePostForm = newValue;
    // 当抽屉从 未开启 ==> 已开启 的各种操作
    if (this.drawer) {
      setTimeout(() => {
        this.renderFromAndToData();
        this.$nextTick(() => {
          (this as any).$refs.activePostForm.clearValidate();
        })
      }, 0)
    }
  }

  private visiblePersonnelValidate = (rule, value, callback) => {
    if (this.visiblePersonnel.length === 0) {
      callback(new Error('请在穿梭框左侧选择触达人员'));
    } else {
      callback();
    }
  }

  private rules: object = {
    name: [{ required: true, message: '请输入消息名称', trigger: 'blur' }],
    type: [{ required: true, message: '请输入消息类型', trigger: 'blur' }],
    content: [
      { required: true, message: '请输入消息内容', trigger: 'blur' },
      { message: '消息内容不能超过200字', max: 200, trigger: 'blur' }
    ],
    level: [{ required: true, message: '请输入消息级别规则', trigger: 'change' }],
    // visiblePersonnel: [{ required: true, message: '请选择触达人员', trigger: 'change', validator: this.visiblePersonnelValidate }],
    rules: [{ required: true, message: '请输入触达规则', trigger: 'change' }],
    remindWay: [{ required: true, message: '请选择触达方式', trigger: 'change' }]
  }

  private typeOptions = [ // 消息类型选项
    // { value: 'system', label: '系统消息' }
    { value: 'transmit', label: '传输中心' },
    { value: 'notice', label: '公告管理' },
    { value: 'mpNotice', label: '工单客户' },
    { value: 'workorderNotice', label: '工单消息' },
    { value: 'qualityCheck', label: '质检消息' }
  ]

  private rulesOptions = [ // 触达规则选项
    { value: 'only', label: '触达一次' }
  ]

  private remindWayOptions = [ // 触达方式选项
    { value: 'system', label: '系统' },
    { value: 'browser', label: '浏览器' }
  ]
  // #endregion

  // #region 页面全局函数
  private renderFromAndToData () {
    // 初始化穿梭框
    const tree = [
      { id: 111, pid: 0, label: '角色', field: 'visibleRole', disabled: false, children: [] },
      { id: 222, pid: 0, label: '技能组', field: 'visibleQueue', disabled: false, children: [] },
      { id: 333, pid: 0, label: '座席', field: 'visibleAgent', disabled: false, children: [] }
    ]
    this.transferFromData = deepClone(tree); // 左侧
    this.visiblePersonnel = deepClone(tree); // 右侧
    if (this.postForm.visiblePersonnel) {
      for (const v of (this.$store as Store<any>).state.common.publicCache.roleList) { // 角色
        if (this.postForm.visiblePersonnel.visibleRole.includes(v._id)) { // 已选，右侧
          this.visiblePersonnel[0].children.push({
            id: v._id,
            pid: 111,
            label: v.name
          })
        } else { // 未选，左侧
          this.transferFromData[0].children.push({
            id: v._id,
            pid: 111,
            label: v.name
          })
        }
      }
      for (const v of (this.$store as Store<any>).state.common.publicCache.queueList) { // 技能组
        if (this.postForm.visiblePersonnel.visibleQueue.includes(v._id)) { // 已选，右侧
          this.visiblePersonnel[1].children.push({
            id: v._id,
            pid: 222,
            label: v.name
          })
        } else { // 未选，左侧
          this.transferFromData[1].children.push({
            id: v._id,
            pid: 222,
            label: v.name
          })
        }
      }
      for (const v of (this.$store as Store<any>).state.common.publicCache.userList) { // 座席
        if (this.postForm.visiblePersonnel.visibleAgent.includes(v.agentNumber)) { // 已选，右侧
          this.visiblePersonnel[2].children.push({
            id: v.agentNumber,
            pid: 333,
            label: v.agentName
          })
        } else { // 未选，左侧
          this.transferFromData[2].children.push({
            id: v.agentNumber,
            pid: 333,
            label: v.agentName
          })
        }
      }
    }
    // 左侧无子元素的大类，根节点disabled
    for (let i = 0; i < this.transferFromData.length; i++) {
      if (this.transferFromData[i].children.length === 0) {
        this.transferFromData[i].disabled = true
      }
    }
    // 过滤掉右侧穿梭框中，无子元素的大类
    this.visiblePersonnel = this.visiblePersonnel.filter(v => v.children.length > 0);
    // console.log('======= 左边:', this.transferFromData);
    // console.log('======= 右边:', this.visiblePersonnel);
  }

  private openOrCloseDraw () {
    this.drawer = !this.drawer;
  }

  private closeDraw () {
    this.drawer = false;
  }

  // 保存按钮
  private handleConfirm () {
    (this as any).$refs.activePostForm.validate((valid) => {
      if (valid) {
        // 角色
        const visibleRole = this.visiblePersonnel.find(v => v.field === 'visibleRole')
        this.postForm.visiblePersonnel.visibleRole = visibleRole ? visibleRole.children.map(v => v.id) : []
        // 技能组
        const visibleQueue = this.visiblePersonnel.find(v => v.field === 'visibleQueue')
        this.postForm.visiblePersonnel.visibleQueue = visibleQueue ? visibleQueue.children.map(v => v.id) : []
        // 座席
        const visibleAgent = this.visiblePersonnel.find(v => v.field === 'visibleAgent')
        this.postForm.visiblePersonnel.visibleAgent = visibleAgent ? visibleAgent.children.map(v => v.id) : []
        // 按事件类型进行emit
        switch (this.drawerType) {
          case 'add':
            this.$emit('handleConfirmAdd', this.activePostForm);
            break;
          case 'edit':
            this.$emit('handleConfirmEdit', this.activePostForm);
            break;
        }
      } else {
        console.log('error submit!!!');
        return false;
      }
    })
  }
  // #endregion

  // #region 触达人员 穿梭框
  // 监听穿梭框组件添加
  private add (fromData, toData, obj) {
    (this as any).$refs.activePostForm.validateField('visiblePersonnel');
    // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
    // 通讯录模式addressList时，返回参数为右侧收件人列表、右侧抄送人列表、右侧密送人列表
    // console.log('fromData:', fromData);
    // console.log('toData:', toData);
    // console.log('obj:', obj);
  }

  // 监听穿梭框组件移除
  private remove (fromData, toData, obj) {
    (this as any).$refs.activePostForm.validateField('visiblePersonnel');
    // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
    // 通讯录模式addressList时，返回参数为右侧收件人列表、右侧抄送人列表、右侧密送人列表
    // console.log('fromData:', fromData);
    // console.log('toData:', toData);
    // console.log('obj:', obj);
  }

  private handleChange (value, direction, movedKeys) {
    console.log(value, direction, movedKeys);
  }
  // #endregion

  // #region 生命周期钩子
  private mounted () {
    this.$nextTick(() => {
      // this.renderTransferDataFunc();
    })
  }
  // #endregion
}
</script>

<style lang="stylus" scoped>
.drawerCont
  .drawerForm
    margin-bottom 55px
    .V7_iconV7tubiao_bangzhu-42
      font-size 12px
      color #a5a5ad
  & >>> .el-select
    width 100%
  & >>> .el-form--label-top .el-form-item__label
    padding-bottom 6px
  & >>> .el-tag.el-tag--info
    overflow hidden
    text-overflow ellipsis
    white-space nowrap
  .visiblePersonnelTransfer
    margin-top 4px
    & >>> .wl-transfer .transfer-title
      font-size 12px
    & >>> .wl-transfer .transfer-main
      overflow hidden
    & >>> .wl-transfer .el-tree
      height calc(100% - 50px)
      // border 1px solid red
      overflow-y auto
    & >>> .custom-tree-node
      font-size 12px
</style>
